package frontmatter

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math/rand"
	"reflect"
	"strings"
	"time"

	"gopkg.in/yaml.v3"
)

// 计算当前毫秒级时间戳 + 随机数的 MD5 哈希值
func getMd5Value() string {
	timestamp := time.Now().UnixMilli()
	randomNumber := rand.Int63()
	hash := md5.Sum([]byte(fmt.Sprintf("%d%d", timestamp, randomNumber)))
	return hex.EncodeToString(hash[:])
}

func ToString(frontmatter Frontmatter) (string, error) {
	newYaml, err := yaml.Marshal(frontmatter)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("---\n%s---\n\n", strings.ReplaceAll(string(newYaml), "\"", "")), nil
}

func Fill(frontmatter Frontmatter, newFrontmatter Frontmatter) Frontmatter {
	// 获取 frontmatter 和 newFrontmatter 的反射值
	val1 := reflect.ValueOf(&frontmatter).Elem()
	val2 := reflect.ValueOf(newFrontmatter)

	// 遍历 frontmatter 的每个字段
	for i := 0; i < val1.NumField(); i++ {
		fieldName := val1.Type().Field(i).Name
		fieldVal := val1.Field(i)
		yamlTag := val1.Type().Field(i).Tag.Get("yaml")
		newTag := val1.Type().Field(i).Tag.Get("new")
		if yamlTag != "-" {
			if newTag == "true" {
				if !reflect.DeepEqual(fieldVal.Interface(), val2.FieldByName(fieldName).Interface()) {
					if fieldVal.CanSet() {
						fieldVal.Set(val2.FieldByName(fieldName))
					}
				}
			} else {
				newVal := val2.FieldByName(fieldName)
				if fieldVal.IsZero() && fieldVal.CanSet() {
					fieldVal.Set(newVal)
				}
			}
		}
	}
	return frontmatter
}
